# Create your views here.
#General
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response

# Json serializer.
from django.core.serializers import serialize
from django.utils.simplejson import dumps, loads

# Application model.
from tracking.models import Device

from db import get_device

from django import forms
 

class DeviceForm(forms.ModelForm):
    class Meta:
        model = Device




def index(request):
    return render_to_response("test.html",{'points':[]})


def device_dispatcher(request,imei=None):
    """
    Receive a new location to be stored at the db, with a IMEI id
    """
    if request.POST:
        return update_device(request, imei)
    else:
        # Return the device information with JSON.
        return HttpResponse(simplejson(get_device({"imei":imei})))    

def update_device(request, imei=None):
    """
    Receive a new location to be stored.
    """
    result = get_device({"imei": imei})
    if "Device" in result:
        result = get_trajectory()    
    
    latitude  = request.REQUEST.get('latitude',None)
    longitude = request.REQUEST.get('longitude',None)
    speed     = request.REQUEST.get('speed',None)
    
    location = Location()
    location.latitude  = latitude
    location.longitude = longitude
    location.speed     = speed

    try:
        location.save()
    except:
        return HttpResponse(simplejson({"error":"Location can't be saved."}))

    return HttpResponse(simplejson({"result":"Location saved."}))
    

def new(request):
    if request.method == 'GET':
        try:
            dev = DeviceForm(request.GET)
            if dev.is_valid():
                device = dev.save(commit = False)
            else:
                return HttpResponse(dumps({'device':'Invalid data.'}))
             
            device.save()
            return HttpResponse(dumps({'device':serialize('json',(device,))}))
        except:
            return HttpResponse(dumps({'error':'Some error creating the device.'}))
    else:
        return HttpResponse(dumps({'error':'We need some data to create the new device.'}))
